﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewLandOY20
{
    public delegate void ShowMsgDelegate(string info);

    /// <summary>
    /// 串口配置类，开启关闭串口、使用委托将串口获取的数据传输到UI
    /// </summary>
    class MySerialConnect
    {
        
        public ShowMsgDelegate myShowMsgDelegate;
        private SerialPort myCom = null;

        public MySerialConnect()
        {
            myCom = new SerialPort();
        }

        public bool OpenPort(string iPort, int iBaud, int iDataBits, Parity iParity, StopBits iStopBits)
        {
            try
            {
                if(myCom != null && myCom.IsOpen)
                {
                    myCom.Close();
                }
                myCom.PortName = iPort;
                myCom.BaudRate = iBaud;
                myCom.DataBits = iDataBits;
                myCom.Parity = iParity;
                myCom.StopBits = iStopBits;

                myCom.ReceivedBytesThreshold = 1;
                myCom.DataReceived += DataRecevier;

                myCom.Open();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ClosePort()
        {
            try
            {
                if (myCom != null && myCom.IsOpen)
                {
                    myCom.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        // 接收到数据时执行的方法， 使用委托在UI线程上显示数据
        public void DataRecevier(Object sender, SerialDataReceivedEventArgs e)
        {
            byte[] recv = new byte[1024];
            int count = 0;
            while(myCom.BytesToRead > 0)
            {
                recv[count] = (byte)myCom.ReadByte();
                count++;
                if (count >= 1024)
                {
                    count = 0;
                    myCom.DiscardInBuffer();
                    return;
                }
            }
            if(count > 0)
            {
                myShowMsgDelegate(Encoding.ASCII.GetString(recv, 0, count));
            }
        }
    }
}
